package com.two.service.order.orderservice.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.two.common.util.CommonResult;
import com.two.service.order.entity.Orders;
import com.two.service.order.mapper.OrdersMapper;
import com.two.service.order.orderservice.IOrdersService;
import com.two.service.order.vo.*;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 汪瑞明
 * @since 2022-09-01
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

   /* @Override
    public CommonResult buy(GoodsVo goodsVo) {

        return null;
    }*/

    // PC端查询订单并完成分页
    @Override
    public CommonResult search(Integer currentPage, Integer pageSize, Orders orders, String token) {
        // 根据token获取登录者的角色id
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        Integer roleid = (Integer) user.get("roleid");
        String usermonicker = orders.getUsermonicker();

        Page<Orders> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();

        wrapper.isNotNull("alipay_no");
       // wrapper.eq("alipay_no","已支付");
        wrapper.eq("remark",0);
         // 模糊查询
        if (StringUtils.hasText(usermonicker)){
            wrapper.like("usermonicker",orders.getUsermonicker());


        }

        // 查询订单号不重复的订单
        wrapper.select("DISTINCT ordersid,usermonicker,total_price,alipay_no,order_time,payment_time,status");

         if (roleid==2){  // 店家
            System.out.println("user==========>"+user);
            // 获得订单中的餐厅
            Integer rid = (Integer) user.get("rid");
            wrapper.eq("rid",rid);
        }

        ordersMapper.selectPage(page,wrapper);
        return new CommonResult(2000,"查询成功",page);


    }

    // 删除订单
    @Override
    public CommonResult delete(String id) {
        int i = ordersMapper.deleteById(id);
        if (i==1){
            return new CommonResult(2000,"删除成功",null);
        }
            return new CommonResult(5000,"删除失败",null);

    }

    //手机端查看订单详情
    @Override
    public CommonResult orderDetails(String ordersid) {

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("ordersid",ordersid);
       /* Map<String,Object> map = new HashMap<>();
        System.out.println();
        map.put("ordersid", ordersid);
        List<Orders> orders = ordersMapper.selectByMap(map);*/
        List<Orders> orders = ordersMapper.selectList(wrapper);
        if (orders!=null){
            return new CommonResult(2000,"查询订单详情成功",orders);
        }
        return new CommonResult(5000,"查询订单详情失败",null);
    }

    // 购物车支付
    @Override
    public CommonResult payMoney(String totalPrice, ShopcarVo[] shopcar) {
        Orders orders = null;
      int length = shopcar.length;
        if (length<1){
            return new CommonResult(5000,"购买的商品不能为空",null);
        }
        // 订单id
         String ordersId = DateUtil.format(new Date(), "yyyyMMdd") + System.currentTimeMillis();
        // String ordersId = =DateUtil.format(new Date(),"yyyyMMdd")+System.currentTimeMillis();
        for (int i = 0; i < length; i++) {
            orders= new Orders();
            orders.setMenuImg(shopcar[i].getMenuImg());
            orders.setDishName(shopcar[i].getDishName());
            orders.setRid(shopcar[i].getRid());
            orders.setDisPrice(shopcar[i].getDisPrice());
            orders.setOrderTime(new Date());
            orders.setUsermonicker(shopcar[i].getUsermonicker());
            orders.setIsDeleted(0);
            orders.setOrdersid(ordersId);
            orders.setSum(shopcar[i].getDishNum());
            orders.setTotalPrice(totalPrice);
            orders.setDishTotalPrice(shopcar[i].getDishTotalPrice());
            orders.setOid(UUID.randomUUID().toString().replace("-",""));
            ordersMapper.insert(orders);
          }

        return new CommonResult(2000,"支付成功",orders);
    }

    // 付款之后更新订单状态
    @Override
    public CommonResult updateState(String tradeNo, String status, String gmtPayment, String alipayTradeNo) {
        int i = ordersMapper.updateState(tradeNo, status, gmtPayment, alipayTradeNo);
        if (i!=0) {
            return new CommonResult(2000, "支付成功", null);
        }
        return new CommonResult(5000, "支付失败", null);
    }

    // 获取支付宝订单流水号
    @Override
    public Orders getByNo(String traceNo) {
        Orders orders = ordersMapper.getByNo(traceNo);
        return orders;
    }

    // 商家同意退款更新订单支付状态
    @Override
    public CommonResult updatePayState(String traceNo, String status, String now) {
        now = String.valueOf(new Date());
        int i = ordersMapper.updatePayState(traceNo, status, now);
        if (i!=0) {
            return new CommonResult(2000, "退款成功", null);
        }
        return new CommonResult(5000, "退款失败", null);
    }

    @Override
    public CommonResult shopPay(String totalPrice, RestautantVo[] restautantVo) {

        Orders orders = null;
        int length = restautantVo.length;

        if (length<1){
            return new CommonResult(5000,"购买的商品不能为空",null);
        }
        // 订单id
        String ordersId = DateUtil.format(new Date(), "yyyyMMdd") + System.currentTimeMillis();
        Date date = new Date();
        // String ordersId = =DateUtil.format(new Date(),"yyyyMMdd")+System.currentTimeMillis();
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < restautantVo[i].getShopcar().size(); j++) {
                orders= new Orders();
                orders.setMenuImg(restautantVo[i].getShopcar().get(j).getMenuImg());
                orders.setDishName(restautantVo[i].getShopcar().get(j).getDishName());
                orders.setRid(restautantVo[i].getShopcar().get(j).getRid());
                orders.setDisPrice(restautantVo[i].getShopcar().get(j).getDisPrice());
                orders.setOrderTime(date);
                orders.setUsermonicker(restautantVo[i].getShopcar().get(j).getUsermonicker());
                orders.setIsDeleted(0);
                orders.setProductCode(0);
                orders.setOrdersid(ordersId);
                orders.setSum(restautantVo[i].getShopcar().get(j).getDishNum());
                orders.setTotalPrice(totalPrice);
                orders.setRemark(0);
                // 计算没样菜品的价格
                float disPrice = Float.parseFloat(restautantVo[i].getShopcar().get(j).getDisPrice());
                Integer dishNum = restautantVo[i].getShopcar().get(j).getDishNum();
                String v = String.valueOf(disPrice * dishNum);
                orders.setDishTotalPrice(v);
                orders.setOid(UUID.randomUUID().toString().replace("-",""));
                ordersMapper.insert(orders);
            }
        }

        return new CommonResult(2000,"支付成功",orders);

    }

    // 手机端确认订单页面
    @Override
    public CommonResult confirmPay(String token) {
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        String usermonicker = user.getString("usermonicker");
      /*  QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("usermonicker",usermonicker);
        wrapper.eq("status","待支付");
        List list = ordersMapper.selectList(wrapper);*/
        // 获取该角色所有的待支付的订单
        List<ConfirmPayVo> confirmPayVos =ordersMapper.selectOrder(usermonicker);
        System.out.println(confirmPayVos.toString());
        // 获取所有未支付订单的菜
        List<VegetableVo> vegetableVos = ordersMapper.selectVegetableVo(usermonicker);
        // 将未支付的菜放入对应的订单
        for (int i = 0; i < confirmPayVos.size(); i++) {
            List<VegetableVo> vegetableVos1 = new ArrayList<>();
            for (int j = 0; j < vegetableVos.size(); j++) {
                if (confirmPayVos.get(i).getOrdersid().equals(vegetableVos.get(j).getOrdersid())){
                   vegetableVos1.add(vegetableVos.get(j));
                }
            }
            confirmPayVos.get(i).setVegetableVos(vegetableVos1);
        }
        return new CommonResult(2000,"查询未支付订单成功",confirmPayVos);
    }

    // 手机端 获取订单
    @Override
    public CommonResult findOrders(String token) {
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        String usermonicker = user.getString("usermonicker");

      /*  QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("ordersid","orderTime","totalPrice");*/
        List<PhoneOrdersVo> phoneOrdersVo = ordersMapper.selectOrders(usermonicker);


        return new CommonResult(2000,"查询成功",phoneOrdersVo);
    }

    // 手机端取消订单
    @Override
    public CommonResult deleteByOrdersId(String ordersid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ordersid",ordersid);
        int i = ordersMapper.delete(queryWrapper);
        if (i!=0){
            return new CommonResult(2000,"取消成功",null);
        }
            return new CommonResult(5000,"取消失败",null);

    }

    //  手机端更新客户评论状态
    @Override
    public void updateCommentStatus(PinglunVo pinglunVo) {
        String ordersid = pinglunVo.getOrdersid();
        String dishName = pinglunVo.getDishName();
        Integer rid = pinglunVo.getRid();
        String usermonicker = pinglunVo.getUsermonicker();
        System.out.println(ordersid+"==>"+dishName+"==>"+rid+"==>"+usermonicker);
        int i =  ordersMapper.updateCommentStatus(ordersid,dishName,rid,usermonicker);
        System.out.println("i===>"+i);
    }

    // PC端查看订单详情
    @Override
    public CommonResult orderDetailsByRid(String token, String ordersid) {
        // 获取登陆者的身份
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");

        System.out.println("user====>"+user);

        // 获取查询者的角色
        Integer roleid = user.getInteger("roleid");
        // 设置查询条件
        Map<String,Object> map1 = new HashMap<>();

        map1.put("ordersid",ordersid);

        if(roleid==2){ // 商家
            // 获取该店铺的rid
            Integer rid = user.getInteger("rid");
            map1.put("rid",rid);
        }
        // 根据条件查询订单详情
        List<Orders> orders = ordersMapper.selectByMap(map1);
        if (orders!=null){
            return new CommonResult(2000,"查询订单详情成功",orders);
        }
        return new CommonResult(5000,"查询订单详情失败",null);

    }

    // 手机端用户申请退款修改订单状态为1，表示已发起过退款
    @Override
    public void updateProductCode(String oid) {
        /*QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("product_code",1);
        queryWrapper.select("oid",oid);*/
        int i = ordersMapper.updateProductCode(oid);
        if (i!=0){
            System.out.println("+++++++++>退款成功");
        }

    }

    // 手机端确认收货
    @Override
    public CommonResult recipt(String ordersid) {
        int i = ordersMapper.updateOrdersStutes(ordersid);
        if (i!=0){
            return new CommonResult(2000,"退款成功",null);
        }
        return new CommonResult(5000,"退款失败",null);
    }

    // 查询所有餐厅营业额
    @Override
    public CommonResult findMoney(String token) {

    /*public CommonResult findMoney() {
        System.out.println("=========>进入获取金额");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // get the request
         HttpServletRequest request = requestAttributes.getRequest();

        String s1 = request.toString();
        System.out.println("The s1 is===> " + s1);
        System.out.println("The request is===> " + request);
        System.out.println("The token is===> " + request.getHeader("token"));
            String token = request.getHeader("token");*/

            // 根据token获取登录者的角色id
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        Integer roleid = (Integer) user.get("roleid");

        //  查出订单中所有的销售订单
        List<StatisticVo> list =  ordersMapper.findMoney();
        // 统计每个店铺的销售额
        List<StatisticVo> list1 =  new ArrayList<>();

        if (roleid==2){  // 店家
            // 获得该店家的店铺号
            Integer rid = (Integer) user.get("rid");
            // 根据店铺号查找该店铺销售的菜
            List<StatisticGoodsVo> list2 = ordersMapper.selectGoods(rid);
            // 查询各道菜的销售额
            List<StatisticGoodsVo> list3 = new ArrayList<>();


            for (int i = 0; i < list2.size(); i++) {
                Integer flag = 0;
                if (list3.size()==0){
                    list3.add(list2.get(0));
                }else for (int j = 0; j < list3.size(); j++) {
                    if (list2.get(i).getDishName().equals(list3.get(j).getDishName())) {
                        list3.get(j).setDishTotalPrice(list3.get(j).getDishTotalPrice().add(list2.get(i).getDishTotalPrice()));
                        flag = 1;
                    } else if (j == list3.size() - 1 && flag == 0) {
                        list3.add(list2.get(i));
                    }
                }
            }
            return new CommonResult(2000,"成功",list3);
        }
        for (int i = 0; i < list.size(); i++) {
            Integer flag = 0;
            if (list1.size() == 0) {
                list1.add(list.get(0));
            } else for (int j = 0; j < list1.size(); j++) {
                if (list.get(i).getRestaurantname().equals(list1.get(j).getRestaurantname())) {
                    list1.get(j).setDishTotalPrice(list1.get(j).getDishTotalPrice().add(list.get(i).getDishTotalPrice()));
                    flag = 1;
                } else if (j == list1.size() - 1 && flag == 0) {
                    list1.add(list.get(i));
                }
            }
        }
        return new CommonResult(2000,"成功",list1);
    }

    // 商家确认接单
    @Override
    public CommonResult confirmOrders(Orders[] orders) {
        int j = 0;
        for (int i = 0; i < orders.length; i++) {
            // 修改订单接单状态
            orders[i].setRemark(1);
             j = ordersMapper.updateById(orders[i]);
        }
        if (j!=0){
            return new CommonResult(2000,"接单成功",null);
        }
        return new CommonResult(5000,"接单失败",null);
    }

    @Override
    public CommonResult searchSuccessOrders(Integer currentPage, Integer pageSize, Orders orders, String token) {
        // 根据token获取登录者的角色id
        String s = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(s, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        Integer roleid = (Integer) user.get("roleid");
        String usermonicker = orders.getUsermonicker();

        Page<Orders> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();

        wrapper.isNotNull("alipay_no");
        // wrapper.eq("alipay_no","已支付");
        // wrapper.eq("remark",0);
        wrapper.gt("remark",0);
        // 模糊查询
        if (StringUtils.hasText(usermonicker)){
            wrapper.like("usermonicker",orders.getUsermonicker());
        }

        // 查询订单号不重复的订单
        wrapper.select("DISTINCT ordersid,usermonicker,total_price,alipay_no,order_time,payment_time,status");

        if (roleid==2){  // 店家
            System.out.println("user==========>"+user);
            // 获得订单中的餐厅
            Integer rid = (Integer) user.get("rid");
            wrapper.eq("rid",rid);
        }

        ordersMapper.selectPage(page,wrapper);
        return new CommonResult(2000,"查询成功",page);
    }
}
